package cn.ywyself.extend.utils;

import java.net.URLEncoder;
import java.util.*;

/**
 * 签名工具
 *
 * @author : ywyself
 * @created : 2018-10-20 11:30
 */
public class SignUtils {

    public static void main(String[] args) {
        Map<String, String> data = new HashMap<>();
        data.put("attach", "");
        data.put("body", "body");
        data.put("appid", "appid");
        data.put("return_url", "http://www.baidu.com");
        Map<String, String> signData = filterParams(data, false, "appid");
        System.out.println(signData);
        System.out.println(buildPayParams(signData, true));
    }

    /**
     * 参数过滤，过滤空值和指定的key
     *
     * @param payParams 参数
     * @param keepNull  保留空值
     * @param keys      去除指定的key
     */
    public static Map<String, String> filterParams(final Map<String, String> payParams, boolean keepNull, String... keys) {
        if (payParams == null || payParams.size() <= 0) {
            return new HashMap<>();
        }
        Map<String, String> result = new HashMap<>(payParams.size());
        for (String key : payParams.keySet()) {
            String value = payParams.get(key);
            // 是否跳过当前键
            boolean isSkip = false;
            //
            for (String s : keys) {
                if (s.equals(key)) {
                    isSkip = true;
                }
            }
            if (!keepNull && (value == null || "".equals(value))) {
                isSkip = true;
            }
            if (isSkip) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }

    /**
     * 对map中的数据进行ASCII排序，并拼接为queryString格式（key1=val1&key2=val2&key3=val3）
     *
     * @param payParams 参数
     * @param encodeUrl 是否对参数进行URL编码
     */
    public static String buildPayParams(Map<String, String> payParams, boolean encodeUrl) {
        List<String> keys = new ArrayList<>(payParams.keySet());
        Collections.sort(keys);
        StringBuilder stringBuilder = new StringBuilder();
        boolean isFirst = true;
        for (String key : keys) {
            if (isFirst) {
                isFirst = false;
            } else {
                stringBuilder.append("&");
            }
            stringBuilder.append(key).append("=");
            if (encodeUrl) {
                stringBuilder.append(urlEncode(payParams.get(key)));
            } else {
                stringBuilder.append(payParams.get(key));
            }
        }
        return stringBuilder.toString();
    }

    /**
     * URL编码
     *
     * @param str 字符串
     * @return 编码后的字符串
     */
    private static String urlEncode(String str) {
        try {
            return URLEncoder.encode(str, "UTF-8");
        } catch (Throwable e) {
            return str;
        }
    }
}
